package config

import (
	"encoding/json"
	"excel-exporter/types"
	"fmt"
	"os"
	"strconv"
)

// defaultProcessor 默认处理器
func defaultProcessor(data []types.DataRow, exportType string, sheetConfig *types.Sheet) ([]types.DataRow, map[string]interface{}) {
	result := make([]types.DataRow, 0, len(data))
	extra := make(map[string]interface{})
	
	for _, row := range data {
		newRow := make(types.DataRow)
		
		// 复制原始数据
		for k, v := range row {
			newRow[k] = v
		}
		
		result = append(result, newRow)
	}
	
	// 添加顶层额外字段
	
	return result, extra
}

// 常量表导表加字段
func constProcessor(data []types.DataRow, exportType string, sheetConfig *types.Sheet) ([]types.DataRow, map[string]interface{}) {
	result, extra := defaultProcessor(data, exportType, sheetConfig)

	extra["add_const_extra"] = "wtf"

	return result, extra
}

// serverOnlyProcessor 服务端专用处理器
func serverOnlyProcessor(data []types.DataRow, exportType string, sheetConfig *types.Sheet) ([]types.DataRow, map[string]interface{}) {
	result := make([]types.DataRow, 0, len(data))
	extra := make(map[string]interface{})
	
	for _, row := range data {
		newRow := make(types.DataRow)
		
		// 复制原始数据
		for k, v := range row {
			newRow[k] = v
		}
		
		// 添加服务端专用字段
		newRow["server_only_field"] = "server_value"
		newRow["timestamp"] = "2025-11-10 12:00:00"
		// fmt.Println("====================wtf", row["Id"])
		
		result = append(result, newRow)
	}
	
	extra["export_type"] = exportType
	extra["total_count"] = len(result)
	extra["processor"] = "server_only"
	extra["server_info"] = map[string]interface{}{
		"version": "1.0.0",
		"env":     "production",
	}
	
	return result, extra
}

// clientOnlyProcessor 客户端专用处理器
func clientOnlyProcessor(data []types.DataRow, exportType string, sheetConfig *types.Sheet) ([]types.DataRow, map[string]interface{}) {
	result := make([]types.DataRow, 0, len(data))
	extra := make(map[string]interface{})
	
	for _, row := range data {
		newRow := make(types.DataRow)
		
		// 复制原始数据
		for k, v := range row {
			newRow[k] = v
		}
		
		// 添加客户端专用字段
		newRow["client_only_field"] = "client_value"
		newRow["platform"] = "mobile"
		
		result = append(result, newRow)
	}
	
	// 添加顶层额外字段	
	extra["export_type"] = exportType
	extra["total_count"] = len(result)
	extra["processor"] = "client_only"
	extra["client_info"] = map[string]interface{}{
		"sdk_version": "2.1.0",
		"build":       "12345",
	}
	
	return result, extra
}

// loadJSONData 加载JSON数据文件
func loadJSONData(filePath string) (map[string]types.DataRow, error) {
	data, err := os.ReadFile(filePath)
	if err != nil {
		return nil, err
	}
	
	var jsonData types.JSONData
	if err := json.Unmarshal(data, &jsonData); err != nil {
		return nil, err
	}
	
	return jsonData.Data, nil
}

// convertToString 将值转换为字符串
func convertToString(value interface{}) string {
	switch v := value.(type) {
	case string:
		return v
	case int:
		return strconv.Itoa(v)
	case float64:
		return strconv.FormatFloat(v, 'f', -1, 64)
	default:
		return fmt.Sprintf("%v", v)
	}
}